<template>
    <div class="home-container">
        <!-- 内容区域 -->
        <b-container class="bv-example-row">
            <!-- 商品图片区域 -->
            <b-row class="row-box">
                <b-col cols="12" sm="12" md="12" lg="12">
                    <Tabs :animated="false">
                        <TabPane label="图片集">
                            <b-row>
                                <b-col cols="6" sm="6" md="6" lg="3" class="goodsImg">
                                    <img :src="mainImg.gpAddress" preview="1" :preview-text="goodInfo.gTitle">
                                </b-col>
                                <b-col cols="6" sm="6" md="6" lg="3" class="goodsImg" v-for="item in otherImg" :key="item.gpId">
                                    <img :src="item.gpAddress" preview="2" :preview-text="goodInfo.gTitle">
                                </b-col>
                            </b-row>
                        </TabPane>
                    </Tabs>
                </b-col>
            </b-row>
            <!-- 商品信息区域 -->
            <b-row class="row-box">
                <b-col cols="12" sm="12" md="12" lg="12">
                    <div class="goodsInfo">
                        <h5>{{goodInfo.gTitle}}</h5>
                        <p>{{goodInfo.gName}}</p>
                        <p>
                            <span class="now-price">￥{{goodInfo.gPrice}}</span>
                            <s class="old-price">￥{{goodInfo.gOriginalPrice}}</s>
                            <span class="pay-trade">运费：￥{{goodInfo.gFire}}</span>
                            <span class="pay-trade">{{goodInfo.gTrade}}</span>
                            <span class="pay-trade">{{goodInfo.gMode}}</span>
                        </p>
                        <p>
                            <span class="pay-place"><Icon type="ios-pin" /> {{goodInfo.gAddr}}</span>
                            <span class="pay-place"><Icon type="ios-eye" /> {{goodInfo.gViewNum}}</span>
                            <span class="pay-place">{{goodInfo.gLevel}}</span>
                        </p>
                        <p>
                            <span class="pay-place"><Icon type="md-clock" /> {{goodInfo.gCreateTime | dataFormat}}</span>
                            <span class="pay-place">类别：{{type.tName}}</span>
                            <span class="isCollecte" v-if="isCol">
                                <span class="pay-star">
                                    <a href="javascript:void(0);" @click.prevent="cancelCol(goodCollection.gcId)">
                                        <Icon type="md-star" /> 已收藏</a>
                                </span>
                            </span>
                            <span class="isCollecte" v-else>
                                <span class="pay-star">
                                    <a href="javascript:void(0);" @click.prevent="addCol">
                                        <Icon type="md-star-outline" /> 收藏</a>
                                </span>
                            </span>
                        </p>
                        <p v-if="user.uId!=uId">
                            <a class="pay-link" @click.prevent="goBuy"><Icon type="ios-cart" /> 立即购买</a>
                            <a href="javascript:void(0)" class="pay-car" @click.prevent="addShopcar(false)">
                                <Icon type="md-cart" /> 加入购物车</a>
                            <router-link :to="'/addPrivateMsg/' + user.uId + '/' + goodInfo.gId" class="pay-chat">
                            <Icon type="ios-chatbubbles" /> 联系卖家</router-link>
                        </p>
                        <p v-else>
                            <router-link :to="'/updateGoods/' + goodInfo.gId" class="pay-link">
                            <Icon type="ios-brush-outline" /> 编辑</router-link>
                        </p>
                    </div>
                </b-col>
            </b-row>
            <!-- 商品详情区域 -->
            <b-row class="row-box">
                <b-col cols="12" sm="12" md="12" lg="12">
                    <Tabs :animated="false">
                        <TabPane label="商品详情">{{goodInfo.gDesc}}</TabPane>
                    </Tabs>
                </b-col>
            </b-row>
            <!-- 商品留言区域 -->
            <b-row class="row-box">
                <b-col cols="12" sm="12" md="12" lg="12">
                    <Tabs :animated="false">
                        <TabPane label="商品留言">
                          <!-- 发表留言 -->
                          <div class="comment-container">
                            <textarea class="mytext" placeholder="请输入要留言的内容（最多200字哦！）" maxlength="200" v-model="msg"></textarea>
                            <div class="span-two">
                                <span class="little-space">剩余可输入<span class="num">{{ num }}</span>字</span>
                                <div class="btn-com">
                                <Button type="primary" @click="postComment">发表评论</Button>
                                </div>
                            </div>
                          </div>
                          <div class="comment-count" v-if="msgCount>0">{{msgCount}} 条留言</div>
                          <!-- 留言回复列表 -->
                          <!-- 父子组件嵌套传递方法和值  组件嵌套组件，父组件就变了 -->
                          <goods :commentList="commentList" @postReply="postReply" @delete="deleteComment"></goods>
                        </TabPane>
                    </Tabs>
                </b-col>
            </b-row>
        </b-container>
    </div>
</template>

<script>
import goods from '@/components/users/common/Goods.vue'
export default {
  name: 'goodsInfo',
  data () {
    return {
      gId: this.$route.params.gId, // 商品id
      uId: JSON.parse(localStorage.getItem('user')).uId, // 用户Id
      goodInfo: '', // 商品详情
      type: '', // 类别详情
      user: '', // 用户信息
      imgList: [], // 图片列表
      mainImg: '', // 主图
      otherImg: [], // 其他图片
      isCol: false, // 判断此商品是否被用户收藏
      goodCollection: '', // 商品收藏信息
      commentList: [], // 评论列表
      msg: '', // 评论输入的内容
      flag: false,
      msgCount: 0 // 评论回复总数
    }
  },
  created () {
    this.findById()
    this.findPictures()
    this.collection()
    this.findComments()
    this.findCommentCount()
  },
  methods: {
    // 根据id查找此商品基本信息
    findById () {
      // 新增此商品浏览量
      this.$axios({
        url: 'goods/updateViewNum',
        method: 'get',
        params: {
          gId: this.gId
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.$axios({
            url: 'goods/findById/' + this.gId,
            method: 'get'
          }).then(res => {
            if (res.data.code === 200) {
              this.goodInfo = res.data.object
              this.user = res.data.object.users
              this.findByTypeId()
              if (res.data.object.gTrade === 1) {
                this.goodInfo.gTrade = '一口价'
              } else {
                this.goodInfo.gTrade = '可砍价'
              }
              if (res.data.object.gMode === -1) {
                this.goodInfo.gMode = '审核失败'
              } else if (res.data.object.gMode === 0) {
                this.goodInfo.gMode = '审核中'
              } else if (res.data.object.gMode === 1) {
                this.goodInfo.gMode = '售卖中'
              } else if (res.data.object.gMode === 2) {
                this.goodInfo.gMode = '已下架'
              }
            }
          }).catch(error => {
            console.log(error)
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 根据类别id查找此商品类别详情
    findByTypeId () {
      this.$axios({
        url: 'types/findById/' + this.goodInfo.gTid,
        method: 'get'
      }).then(res => {
        if (res.data.code === 200) {
          this.type = res.data.object
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 根据商品id查询此商品下的所有图片
    findPictures () {
      this.$axios({
        url: 'goodsPicture/findByGoodsId/' + this.gId,
        method: 'get'
      }).then(res => {
        if (res.data.code === 200) {
          this.imgList = res.data.list
          this.imgList.forEach(item => {
            if (item.gpIsCover === 1) {
              this.mainImg = item
            } else {
              this.otherImg.push(item)
            }
          })
          // vue-photo-preview 如果数据是异步获取回来的，会出现不管你怎么点击，都不会出现效果。需要在你成功获取数据回来之后，加上 this.$previewRefresh() ，刷新重置一下
          this.$previewRefresh()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 根据商品id和用户id查看该商品是否被收藏
    collection () {
      this.$axios({
        url: 'goodsCollection/findByAllId',
        method: 'get',
        params: {
          gcGid: this.gId,
          gcUid: this.uId
        },
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          // 判断收藏状态
          this.goodCollection = res.data.object
          if (this.goodCollection === '' || this.goodCollection == null) {
            this.isCol = false
          } else {
            this.isCol = true
          }
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 新增收藏
    addCol () {
      this.$axios({
        url: 'goodsCollection/save',
        method: 'post',
        params: {
          gcGid: this.gId,
          gcUid: this.uId
        },
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.collection()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 取消收藏
    cancelCol (id) {
      this.$axios({
        url: 'goodsCollection/deleteById/' + id,
        method: 'get',
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.collection()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    /**
     *  添加购物车
     * 1.如果购物车中之前就已经有这个对应的商品了，就需要提示用户此商品已存在于购物车中
     * 2.如果没有，直接添加商品到购物车中
     */
    addShopcar (nodesc) {
      this.$axios({
        url: 'shopcar/save',
        method: 'post',
        params: {
          sUid: this.uId,
          sGid: this.gId
        },
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          // 添加购物车成功
          this.$Notice.success({
            title: res.data.msg,
            render: h => {
              return h('div', [
                h('p', this.goodInfo.gTitle),
                h('a', {
                  attrs: {
                    href: 'http://localhost:8081/#/shopCar'
                  },
                  on: {
                    click: () => {
                      this.$router.push({ path: '/shopCar' })
                    }
                  }
                }, '去购物车查看')
              ])
            }
          })
        } else if (res.data.code === 401) {
          // 购物车中已有此商品
          this.$Notice.info({
            title: '添加购物车失败',
            render: h => {
              return h('div', [
                h('p', res.data.msg),
                h('a', {
                  attrs: {
                    href: 'http://localhost:8081/#/shopCar'
                  },
                  on: {
                    click: () => {
                      this.$router.push({ path: '/shopCar' })
                    }
                  }
                }, '去购物车查看')
              ])
            }
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 根据商品id查询该商品下的所有评论
    findComments () {
      this.$axios({
        url: 'goodsComment/findByGoodId/' + this.gId,
        method: 'get'
      }).then(res => {
        if (res.data.code === 200) {
          this.commentList = res.data.list
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 发表一级评论留言
    postComment () {
      // 校验评论内容是否为空
      if (this.msg.trim().length === 0) {
        return this.$Message.error('留言内容不能为空哦!')
      }
      if (this.uId === '' || this.uId === null) {
        this.$router.push({ path: '/login' })
      }
      this.$axios({
        url: 'goodsComment/save',
        method: 'post',
        params: {
          gcGid: this.gId,
          gcUid: this.uId,
          gcContent: this.msg
        },
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.findComments()
          this.msg = ''
          this.findCommentCount()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 发表评论留言回复
    postReply (id, uName, reply) {
      // 校验评论内容是否为空
      if (reply.trim().length === 0) {
        return this.$Message.error('留言内容不能为空哦!')
      }
      if (this.uId === '' || this.uId === null) {
        this.$router.push({ path: '/login' })
      }
      this.$axios({
        url: 'goodsComment/save',
        method: 'post',
        params: {
          gcGid: this.gId,
          gcUid: this.uId,
          gcContent: '@' + uName + '：' + reply,
          gcParentid: id
        },
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.findComments()
          this.findCommentCount()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 根据评论id删除此评论
    deleteComment (id) {
      this.$axios({
        url: 'goodsComment/deleteById/' + id,
        method: 'get',
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.findComments()
          this.findCommentCount()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 查找评论留言数
    findCommentCount () {
      this.$axios({
        url: 'goodsComment/findCountsByGid/' + this.gId,
        method: 'get',
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.msgCount = res.data.object
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 点击立即购买先将此商品加入购物车，然后跳至确认订单页面
    goBuy () {
      this.$axios({
        url: 'shopcar/save',
        method: 'post',
        params: {
          sUid: this.uId,
          sGid: this.gId
        },
        headers: {
          Authorization: localStorage.getItem('token')
        }
      }).then(res => {
        if (res.data.code === 200) {
          // 添加购物车成功，将购物车商品设置为选中，然后去确认订单页面
          this.$axios({
            url: 'shopcar/updateCheckedByUidAndGid/',
            method: 'get',
            params: {
              uId: this.uId,
              gId: this.gId
            },
            headers: {
              Authorization: localStorage.getItem('token')
            }
          }).then(res => {
            if (res.data.code === 200) {
              this.$router.push({ path: `/imConfirmOrder/${this.gId}` })
            }
          }).catch(error => {
            console.log(error)
          })
        } else if (res.data.code === 401) {
          // 购物车中已有此商品，判断是否选中
          this.$axios({
            url: 'shopcar/findByGidAndUid/',
            method: 'get',
            params: {
              uId: this.uId,
              gId: this.gId
            },
            headers: {
              Authorization: localStorage.getItem('token')
            }
          }).then(res => {
            if (res.data.code === 200) {
              if (res.data.object.sChecked === 0) {
                this.$axios({
                  url: 'shopcar/updateCheckedByUidAndGid/',
                  method: 'get',
                  params: {
                    uId: this.uId,
                    gId: this.gId
                  },
                  headers: {
                    Authorization: localStorage.getItem('token')
                  }
                }).then(res => {
                  if (res.data.code === 200) {
                    this.$router.push({ path: `/imConfirmOrder/${this.gId}` })
                  }
                }).catch(error => {
                  console.log(error)
                })
              } else {
                this.$router.push({ path: `/imConfirmOrder/${this.gId}` })
              }
            }
          }).catch(error => {
            console.log(error)
          })
        }
      }).catch(error => {
        console.log(error)
      })
    }
  },
  computed: {
    // 剩余可输入字数
    num () {
      if (this.msg.trim().length > 0) {
        // eslint-disable-next-line radix
        return parseInt(200 - this.msg.trim().length)
      }
      return 200
    }
  },
  components: {
    goods
  }
}
</script>

<style scoped>
.comment-count {
  padding: 15px 0;
}
.comment-container h5{
        margin-bottom: 0.9rem;
    }
.comment-container{
    margin-top: 1.5rem;
}
.mytext{
    padding: 10px 15px;
    outline: 0;
    width: 100%;
    font-size: 14px;
    margin:0;
    height:90px;
    background-image: url('../../../assets/imgs/comment.gif');
    background-repeat: no-repeat;
    background-position: bottom right;
    background-size: 250px 45px;
    border-radius: 3px;
}
.span-two{
    display: flex;
    justify-content: space-between;
}
.span-two .btn-com{
    margin-top: 0.5rem;
}
.span-two .little-space{
    font-size: 13px;
    color:#888;
}
.num{
    color: #eb2f96;
}

.goodsInfo {
    height:auto;
}
.goodsInfo h5 {
    font-size: 16px;
}
.goodsImg {
    margin-bottom: 15px;
    width: 100%;
    height:auto;
}
.goodsImg img {
    width: 100%;
    height:auto;
    cursor: pointer;
}
.now-price{
    color:#f30;
    margin-right: 20px;
}
.old-price{
    color:rgb(112, 112, 112);
}
.pay-trade{
    margin-left: 20px;
}
.pay-place{
    color:rgb(13, 121, 223);
    margin-right: 20px;
}
.pay-star a{
    color:rgb(250, 157, 18);
}
.pay-link{
    color:#fff;
    background-color: #f3352b;
    border-radius: 5px;
    padding: 8px 10px;
    font-size: 12px;
    margin-right: 12px;
}
.pay-car{
    color:#fff;
    background-color: #18b566;
    border-radius: 5px;
    padding: 8px 10px;
    font-size: 12px;
    margin-right: 12px;
}
.pay-chat{
    color:#fff;
    background-color: #2d8cf0;
    border-radius: 5px;
    padding: 8px 10px;
    font-size: 12px;
}
.goodsInfo .ivu-icon{
    font-size: 18px;
}
.row-box{
    background: #fff;
    padding: 15px 5px;
    margin-bottom: 15px;
}
</style>
